﻿/*
   RxInputManager
   Copyright 2011 Jordan Neumeyer

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   
   File: IRxDevice.cs 
 */
using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using RxInputManager.Interfaces;

namespace RxInputManager.Devices
{
    // ToDo:
    // Figure out how I want to do scheduling.
    // Add proper disposing...
    public abstract class RxDevice<T> : IRxDevice, IDisposable
    {
        protected string deviceName;
        public string DeviceName { get { return deviceName; } protected set { deviceName = value; } }

        protected readonly Subject<T> subject;
        protected IConnectableObservable<T> baseEvent;
        protected IDisposable disposed;

        protected RxDevice() : this(RxInputScheduler.Scheduler)
        {
            
        }

        protected RxDevice(IScheduler scheduler)
        {
            subject = new Subject<T>();
            baseEvent = subject
                               //.ObserveOn(scheduler)
                               .Publish();
            disposed = baseEvent.Connect();
            
            //subject.Dispose();
        }

        public void PushNextEvent(T value)
        {
            subject.OnNext(value);
        }
       

        public virtual void DisableEvents()
        {
            if (null != disposed)
            {
                Console.WriteLine("Events Stopped for device {0}!", DeviceName);
                disposed.Dispose();
                disposed = null;
            }
        }

        public virtual void EnableEvents()
        {
            if (null == disposed)
            {
                Console.WriteLine("Events Started for {0}!,", DeviceName);
                disposed = baseEvent.Connect();
            }
        }

        abstract public bool IsAttached
        {
            get;
        }

        public virtual void Update()
        {
            subject.OnNext(CurrentState);
            previousState = CurrentState;
        }
        
        protected T previousState;
        abstract protected T CurrentState { get; }

        public virtual void Dispose()
        {
            if(null != subject) subject.Dispose();
        }
    }
}
